<template>
  <div v-loading="loading">
    <div class="text-right mb-2">
      <el-button size="small" :disabled="loading" @click="handleViewContract">查看合同</el-button>
      <el-button size="small" :disabled="loading" @click="handleFlow">审批流程</el-button>
      <el-button
        size="small"
        icon="el-icon-printer"
        v-show="!editable"
        :disabled="loading"
        @click="handlePrint"
      >
        打印
      </el-button>
      <el-button size="small" icon="el-icon-download" :loading="loading" @click="exportDocx">
        导出
      </el-button>
    </div>

    <div :id="printId">
      <approve-info :related="related"></approve-info>
      <template v-for="(approve, index) of approval">
        <component
          v-if="approve.show"
          v-bind="$attrs"
          :key="index"
          :is="approve.cmpt"
          :view-mode="viewMode"
          :related-data="related"
          :approve-data="approve"
          @success="handleSuccess"
          @dismiss="handleDismiss"
          @get-type="getTypeData"
        ></component>
      </template>

      <flow-dialog :title="flowName" :visible.sync="flowVisible" :flow-key="flowKey"></flow-dialog>
      <el-dialog
        :visible.sync="contractVisible"
        :close-on-click-modal="false"
        :before-close="berforClose"
        append-to-body
        top="30px"
        width="80%"
      >
        <contract-guard-view :query-id="contractViewId"></contract-guard-view>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { printA4 } from '@vimi/utils-tool'
import FlowDialog from '@/credit/components/flow/ViewDialog'
import { getRelated } from '@/credit/views/county/unionProvince/components/projectApprove/index'
import {
  getApproveProcess,
  enumLoanVarieties,
  wfKey,
} from '@/credit/views/city/self/components/contractApprove/index'
import ApproveCommon from '@/credit/views/city/self/components/contractApprove/ApproveCommon'
import ApproveInfo from '@/credit/views/city/self/components/contractApprove/ApproveInfo'
import ApproveRes from '@/credit/views/city/self/components/contractApprove/ApproveRes'
import { mapGetters } from 'vuex'
import { docxTemplateExport } from '@vimi/utils-tool'
import ContractGuardView from '@/credit/views/county/unionProvince/components/ContractGuardView'
export default {
  components: {
    FlowDialog,
    ApproveCommon,
    ApproveInfo,
    ApproveRes,
    ContractGuardView,
  },
  props: {
    queryId: {
      type: String,
      required: true,
    },
    viewMode: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      wfKey,
      flowKey: wfKey,
      loading: false,
      approval: [],
      related: {},
      flowVisible: false,
      guadTypes: [],
      busContracts: [],
      contractVisible: false,
      contractViewId: '',
    }
  },
  computed: {
    ...mapGetters(['entrustContract', 'enumOrgClassObj', 'user']),
    // 是否已经提交委托担保合同
    contractId() {
      return this.entrustContract.entrust_contract_id
    },
    hasContract() {
      return !!this.contractId
    },
    editable() {
      return !this.viewMode && this.approval.some(it => it.editable)
    },
    flowName() {
      const { approval } = this
      return approval.length ? approval[0].process.workflow_name : '流程'
    },
    printId() {
      return `${this.queryId}-contract-approve`
    },
    // 合同期间
    loadPeriod() {
      return (
        (this.entrustContract.load_date || '- ') +
        '至' +
        (this.entrustContract.load_end_date || ' -')
      )
    },
  },
  watch: {
    queryId: {
      handler: function () {
        this.getData()
      },
      immediate: true,
    },
  },
  created() {},
  methods: {
    handleViewContract() {
      this.contractViewId = this.queryId
      this.contractVisible = true
    },
    berforClose() {
      this.contractViewId = ''
      this.contractVisible = false
    },
    getTypeData(data) {
      if (data.type === 'guadTypes') {
        this.guadTypes = data.data || []
      } else if (data.type === 'busContracts') {
        this.busContracts = data.data
      }
    },
    exportDocx() {
      this.loading = true
      const fileName = '合同审批表'
      const templaterUrl = '/static/files/合同审批.docx'
      const tags = {
        related: {
          ...this.related,
          loadVarietiesStr: enumLoanVarieties[this.entrustContract.loan_varieties] || '',
          orgClassName: this.enumOrgClassObj[this.related.org_class] || '',
          loadPeriod: this.loadPeriod,
        },
        entrustContract: this.entrustContract,
        guadTypes: this.guadTypes,
        busContracts: this.busContracts,
        approval: this.approval.map(item => {
          item.record.map(item => {
            item.approvalOption = item.approval_option.replace(/<[^>]+>/g, '')
            item.approvalTime = this.$utils.dateFormat(item.approval_time, 'yyyy年MM月dd日')
            return item
          })
          return item
        }),
      }
      docxTemplateExport({
        templaterUrl,
        tags,
        fileName,
      })
        .then(() => {
          this.$message.success('导出成功')
        })
        .catch(() => {
          this.$message.error('导出失败')
        })
        .finally(() => {
          this.loading = false
        })
    },
    getData() {
      const { queryId } = this
      if (!queryId) {
        return
      }

      this.loading = true
      return Promise.all([
        getRelated(queryId),
        getApproveProcess(queryId, this.user),
        this.$store.dispatch('getEntrustContract', queryId),
        this.$store.dispatch('getGuardsData', queryId),
      ])
        .then(([related, approval, _contract]) => {
          this.related = related
          const data = approval[0] ?? {}
          const rekey = data.process?.wfn_key ?? null
          this.approval = approval.map(item => {
            if (item.process?.wfn_key !== rekey) {
              item.rekey = rekey
            }
            return item
          })
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleSuccess(res) {
      this.$emit('success', res)
    },

    handleDismiss() {
      this.$emit('dismiss')
    },
    handleFlow() {
      this.flowVisible = true
    },
    handlePrint() {
      printA4(
        document.getElementById(this.printId).innerHTML,
        `
        .vertical-align-middle td {vertical-align: middle;}
        .option {min-height: 7rem;}
      `
      )
    },
  },
}
</script>
<style lang="scss" scoped></style>
